<template>
  <div class="login-container">
    <div style="position: fixed;bottom: 20px;left: 13px;z-index: 1000;display: flex">
      <div v-for="(item,index) in qrCodeList" :key="index" style="margin-right: 15px">
        <el-image
          style="width: 120px;height: 120px"
          :src="item.url"
          :preview-src-list="[item.url]"
        />
        <div style="text-align: center;color: #000">{{ item.title }}</div>
      </div>
    </div>
    <div class="login-form">
      <language-select
        id="language-select"
        class="right-menu-item hover-effect"
        style="position: absolute;right: 30px;top: 20px;color: white;font-size: 20px"
      />
      <el-form
        v-if="loginForm.loginType === 'userName'"
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        autocomplete="on"
        label-position="left"
      >
        <div class="title-container">
          <h3 class="title" v-text="shortCompanyName" />
        </div>

        <el-form-item prop="userName">
          <span class="svg-container">
            <i class="el-icon-user-solid" />
          </span>
          <el-input
            ref="userName"
            v-model="loginForm.userName"
            :placeholder="$t('user')+$t('name')"
            name="userName"
            type="text"
            tabindex="1"
            autocomplete="on"
          >
            <i
              v-if="gzhLogin"
              slot="suffix"
              class="fa fa-weixin el-input__icon"
              @click="loginForm.loginType = 'qrcode'"
            />
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <span class="svg-container">
            <i class="el-icon-key" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            :placeholder="$t('password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <i :class="passwordType === 'password' ? 'fa fa-eye-slash':'fa fa-eye'" />
          </span>
        </el-form-item>

        <el-form-item v-if="model=='register'" prop="password">
          <span class="svg-container">
            <i class="el-icon-key" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.repassword"
            :type="passwordType"
            :placeholder="$t('password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <i :class="passwordType === 'password' ? 'fa fa-eye-slash':'fa fa-eye'" />
          </span>
        </el-form-item>

        <el-form-item v-if="model=='register'&& enablePhoneRegister=='true'" prop="phoneNumber">
          <span class="svg-container">
            <i class="el-icon-phone" />
          </span>
          <el-input
            v-model="loginForm.phoneNumber"
            :placeholder="$t('phoneNumber')"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <el-button
              v-if="!isSendAuthCode"
              type="primary"
              @click="getAuthCode('phone')"
              v-text="$t('verificationCode')"
            />
          </span>
        </el-form-item>

        <el-form-item v-if="model=='register'" prop="email">
          <span class="svg-container">
            <i class="el-icon-message" />
          </span>
          <el-input
            v-model="loginForm.email"
            :placeholder="$t('email')"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <el-button
              v-if="!isSendAuthCode"
              type="primary"
              @click="getAuthCode('email')"
              v-text="$t('verificationCode')"
            />
          </span>
        </el-form-item>

        <el-form-item prop="code">
          <span class="svg-container">
            <i class="el-icon-link" />
          </span>
          <el-input
            v-model="loginForm.code"
            :placeholder="$t('verificationCode')"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span v-if="model=='login'" class="second_tp_codes">
            <div id="code" />
          </span>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-button
              v-if="model=='login'"
              :loading="loading"
              type="primary"
              style="margin-bottom:30px;"
              @click="handleLogin"
            >{{ $t('login') }}
            </el-button>
            <el-button
              v-if="model=='login' && enableDemoAccount === 'true'"
              type="primary"
              style="margin-bottom:30px;"
              @click="handleDemoAccountLogin"
            >{{ $t('demo')+$t('user') }}
            </el-button>
            <el-button
              v-if="model=='register'"
              :loading="loading"
              type="primary"
              style="margin-bottom:30px;"
              @click="handleRegister"
            >{{ $t('register') }}
            </el-button>
          </el-col>
          <el-col v-if="model=='login'" :span="6">
            <el-button type="text" style="float: right" @click="resetPassword = true">{{ $t('reset') }}{{
              $t('password')
            }}
            </el-button>
          </el-col>
        </el-row>
        <el-radio-group v-if="enableRegister === 'true'" v-model="model" @change="modelChange">
          <el-radio label="login">{{ $t('login') }}</el-radio>
          <el-radio label="register">{{ $t('register') }}</el-radio>
        </el-radio-group>
        <div class="mt-4">
          <el-checkbox v-model="safeModel" @change="safeModelChange">{{ $t('safe') + $t('model') }}</el-checkbox>
        </div>
      </el-form>
      <div v-else="">
        <el-button type="primary" icon="el-icon-back" circle style="margin: 13px" @click="userNameType" />
        <login-qrcode style="width: 100%;height: 100%" @change="qrcodeLogin" />
      </div>
    </div>
    <div style="position: absolute;bottom: 13px;text-align:center;width: 400px">
      <el-link href="http://beian.miit.gov.cn" target="_blank">
        {{ $t('version') + ':' + appVersion + ' ' + forReferenceInfo }}
      </el-link>
    </div>

    <el-carousel height="100%" style="width: 100%">
      <el-carousel-item v-for="(item,index) in slideShowList" :key="index">
        <el-image
          style="width: 100%; height: 100%"
          :src="item"
          fit="contain"
        />
      </el-carousel-item>
    </el-carousel>

    <el-dialog
      :title="$t('reset')+$t('password')"
      :visible.sync="resetPassword"
      width="600px"
    >
      <reset-password v-if="resetPassword" />
    </el-dialog>

  </div>
</template>

<script>
import LanguageSelect from '@/components/LanguageSelect'
import { getGVerify } from '@/util/login-code'
import { validUsername } from '@/util/validate'
import { failureNotice, successNotice } from '../../util/common'
import { registerUser, sendAuthCode } from '@/api/auth/authUserApi'
import ResetPassword from './components/ResetPassword'
import {
  getAppVersion,
  getCompanyId,
  getEnableDemoAccount,
  getEnablePhoneRegister,
  getEnableRegister,
  getForReferenceInfo,
  getLanguage, getSafeModel,
  getShortCompanyName,
  setLoginFrom,
  setSafeModel
} from '@/util/storage'
import { listCompanyResource } from '@/api/iot/iotCompanyResourceApi'
import LoginQrcode from './components/LoginQrcode'
import { existToken } from '@/api/iot/iotThirdPartyTokenApi'

const hash = {
  'qq.com': 'http://mail.qq.com',
  'gmail.com': 'http://mail.google.com',
  'sina.com': 'http://mail.sina.com.cn',
  '163.com': 'http://mail.163.com',
  '126.com': 'http://mail.126.com',
  'yeah.net': 'http://www.yeah.net/',
  'sohu.com': 'http://mail.sohu.com/',
  'tom.com': 'http://mail.tom.com/',
  'sogou.com': 'http://mail.sogou.com/',
  '139.com': 'http://mail.10086.cn/',
  'hotmail.com': 'http://www.hotmail.com',
  'live.com': 'http://login.live.com/',
  'live.cn': 'http://login.live.cn/',
  'live.com.cn': 'http://login.live.com.cn',
  '189.com': 'http://webmail16.189.cn/webmail/',
  'yahoo.com.cn': 'http://mail.cn.yahoo.com/',
  'yahoo.cn': 'http://mail.cn.yahoo.com/',
  'eyou.com': 'http://www.eyou.com/',
  '21cn.com': 'http://mail.21cn.com/',
  '188.com': 'http://www.188.com/',
  'foxmail.com': 'http://www.foxmail.com',
  'outlook.com': 'http://www.outlook.com'
}
export default {
  name: 'Login',
  components: {
    LanguageSelect,
    LoginQrcode,
    ResetPassword
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      resetPassword: false,
      forReferenceInfo: getForReferenceInfo(),
      slideShowList: [],
      qrCodeList: [],
      appVersion: getAppVersion(),
      enablePhoneRegister: getEnablePhoneRegister(),
      enableRegister: getEnableRegister(),
      enableDemoAccount: getEnableDemoAccount(),
      gzhLogin: false,
      verifyCode: null,
      shortCompanyName: getShortCompanyName(),
      loginForm: {
        userName: '',
        password: '',
        repassword: null,
        phoneNumber: null,
        email: null,
        authCode: null,
        code: null,
        registerType: null,
        isDemoAccount: false,
        loginType: 'userName',
        ticket: null
      },
      model: 'login',
      loginRules: {
        userName: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      isSendAuthCode: false,
      companyId: getCompanyId(),
      tryLoginNum: 0,
      safeModel: getSafeModel()
    }
  },
  watch: {
    $route: {
      handler(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.$i18n.locale = getLanguage() || 'zh'
    this.listCompanyResource()
    this.existToken()
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    this.$refs.userName.focus()
    this.verifyCode = getGVerify('code')
  },
  methods: {
    safeModelChange() {
      setSafeModel(this.safeModel)
    },
    existToken() {
      existToken({
        companyId: this.companyId,
        type: 'gzh'
      }).then(res => {
        const { code } = res
        if (code === '200') {
          this.gzhLogin = true
        }
      })
    },
    listCompanyResource() {
      listCompanyResource({
        type: 'phoneSlideshow',
        companyId: this.companyId,
        status: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const slideShowList = []
          for (const item of data) {
            slideShowList.push(item.url)
          }
          this.slideShowList = slideShowList
        }
      })
      listCompanyResource({
        type: 'qrCode',
        companyId: this.companyId,
        status: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.qrCodeList = data
        }
      })
    },
    userNameType() {
      this.loginForm.loginType = 'userName'
      this.$nextTick(() => {
        this.verifyCode = getGVerify('code')
      })
    },
    checkForm() {
      if (this.loginForm.registerType == null) {
        failureNotice(this, this.$t('verificationCode'))
        return false
      }
      if (
        this.loginForm.userName == null ||
        this.loginForm.password == null ||
        this.loginForm.userName.trim().length < 4 ||
        this.loginForm.password.trim().length < 6
      ) {
        failureNotice(this, this.$t('user') + this.$t('name') + this.$t('password'))
        return false
      }
      if (
        this.loginForm.registerType === 'email' &&
        !this.regEmail(this.loginForm.email)
      ) {
        failureNotice(this, this.$t('email'))
        return false
      }
      if (
        this.loginForm.registerType === 'phone' &&
        !this.regMobile(this.loginForm.phoneNumber)
      ) {
        failureNotice(this, this.$t('phoneNumber'))
        return false
      }
      if (this.loginForm.password === '') {
        failureNotice(this, this.$t('password'))
        return false
      }
      if (this.loginForm.repassword === '') {
        failureNotice(this, this.$t('password'))
        return false
      }
      if (this.loginForm.password !== this.loginForm.repassword) {
        failureNotice(this, this.$t('password') + this.$t('different'))
        return false
      }
      if (this.loginForm.code !== this.loginForm.authCode) {
        failureNotice(this, this.$t('verificationCode'))
        return false
      }
      return true
    },
    handleRegister() {
      if (!this.checkForm()) {
        return false
      }
      registerUser({
        userName: this.loginForm.userName,
        password: this.loginForm.password,
        email: this.loginForm.email,
        phoneNumber: this.loginForm.phoneNumber,
        registerType: this.loginForm.registerType,
        companyId: this.companyId
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
      })
    },
    // 邮箱正则
    regEmail(email) {
      const regEmail = /^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$/
      return !!regEmail.test(email)
    },

    // 手机号正则
    regMobile(mobile) {
      const regMobile = /^1(3|4|5|7|8)\d{9}$/ // 手机号码格式：1开头接着3或4或5或7或8接着9位
      return !!regMobile.test(mobile)
    },
    getAuthCode(registerType) {
      this.loginForm.registerType = registerType
      switch (registerType) {
        case 'email':
          if (!this.regEmail(this.loginForm.email)) {
            failureNotice(this, this.$t('email') + this.$t('error'))
            return false
          }

          const mail = this.loginForm.email.split('@')[1] // 获取邮箱域
          for (const j in hash) {
            if (j === mail) {
              sendAuthCode({
                email: this.loginForm.email,
                registerType: registerType,
                companyId: this.companyId
              }).then(res => {
                const { code, data } = res
                if (code === '200') {
                  successNotice(this, '邮件发送成功，请进入邮箱获取验证码')
                  this.loginForm.authCode = data
                  setTimeout(function() {
                    this.isSendAuthCode = true
                  }, 15000)
                  window.open(hash[mail])
                }
              })
            }
          }
          break
        case 'phone':
          if (!this.regMobile(this.loginForm.phoneNumber)) {
            failureNotice(this, this.$t('phoneNumber') + this.$t('error'))
            return false
          }
          this.isSendAuthCode = true
          sendAuthCode({
            phoneNumber: this.loginForm.phoneNumber,
            registerType: registerType,
            companyId: this.companyId
          }).then(res => {
            const { code, data } = res
            if (code === '200') {
              successNotice(this, '发送成功，请输入验证码')
              this.loginForm.authCode = data
            }
          })
          break
        default:
          failureNotice(this)
      }
    },
    modelChange() {
      if (this.model === 'login') {
        this.$nextTick(function() {
          this.verifyCode = getGVerify('code')
        })
      }
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && (key >= 'a' && key <= 'z')) ||
          (!shiftKey && (key >= 'A' && key <= 'Z'))
        ) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.reset.focus()
      })
    },
    handleDemoAccountLogin() {
      this.loginForm.isDemoAccount = true
      this.handleLogin()
    },
    qrcodeLogin(data) {
      this.loginForm.ticket = data
      this.qrcodeLoginFunction()
    },
    qrcodeLoginFunction(data) {
      this.loading = true
      this.$store
        .dispatch('user/login', this.loginForm)
        .then(() => {
          this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
          this.loading = false
        })
        .catch(() => {
          if (this.tryLoginNum < 15) {
            setTimeout(() => {
              this.tryLoginNum = this.tryLoginNum + 1
              this.qrcodeLoginFunction()
            }, 2000)
          } else {
            this.tryLoginNum = 0
            this.loading = false
          }
        })
    },
    handleLogin() {
      if (!this.loginForm.isDemoAccount) {
        if (
          this.loginForm.code != null &&
          this.verifyCode.validate(this.loginForm.code)) {
        } else {
          failureNotice(this, '验证码错误')
          return false
        }
        setLoginFrom('user')
      } else {
        setLoginFrom('demo')
      }

      this.$refs.loginForm.validate(valid => {
        if (valid || this.loginForm.isDemoAccount) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              console.log(this.redirect)
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }

  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

/* reset element-ui css */
.login-container {

  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #00bcf9;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  display: flex;
  display: -webkit-flex;
  flex-direction: row-reverse;
  align-items: stretch;
  justify-content: space-between;
  position: relative;

  .login-form {
    background: #2d3a4b;
    width: 550px;
    padding: 100px 35px 0;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 13px;
    top: 9px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .second_tp_codes {
    position: absolute;
    top: 1px;
    right: 0px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

}
</style>
